﻿//INSTANT C# NOTE: Formerly VB project-level imports:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;

using System.Security.Cryptography.X509Certificates;

namespace FederationMetadataEditor
{
	public partial class frmSelectCertificateFile
	{

		internal frmSelectCertificateFile()
		{
			InitializeComponent();
		}
		private X509Certificate2 _selectedSigningCertificate = null;
		public X509Certificate2 selectedSigningCertificate
		{
			get
			{
				return _selectedSigningCertificate;
			}
			set
			{
				_selectedSigningCertificate = value;
			}
		}

		private void cmdOK_Click(object sender, System.EventArgs e)
		{
			try
			{
				if (rbCER.Checked)
				{
					if (System.IO.File.Exists(fldCERFile.Text))
					{
						selectedSigningCertificate = (X509Certificate2)X509Certificate2.CreateFromCertFile(fldCERFile.Text);
					}
					else
					{
						MessageBox.Show("Couldn't find the specified CER file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
				else
				{
					byte[] cert = null;
					if (System.IO.File.Exists(fldPFXFile.Text))
					{
						cert = System.IO.File.ReadAllBytes(fldPFXFile.Text);
						if (!(string.IsNullOrEmpty(this.fldPFXPassword.Text.Trim())))
						{
							selectedSigningCertificate = new X509Certificate2(cert, this.fldPFXPassword.Text);
						}
						else
						{
							selectedSigningCertificate = new X509Certificate2(cert);
						}
					}
					else
					{
						MessageBox.Show("Couldn't find the specified PFX file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
			catch (Exception ex)
			{
				//TODO: catch certificate related exceptions and change the display message
				MessageBox.Show("Error reading the specified certificate");
			}
		}

		private void rbPFX_CheckedChanged(object sender, System.EventArgs e)
		{
			this.PFXFileGroupBox.Enabled = rbPFX.Checked;
		}

		private void rbCER_CheckedChanged(object sender, System.EventArgs e)
		{
			this.CERFileGroupBox.Enabled = rbCER.Checked;
		}

		private void cmdSelectPFXFile_Click(object sender, System.EventArgs e)
		{
			OpenFileDialog openFileDlg = new OpenFileDialog {Title = "Select a PFX file", Filter = "PFX Certificate|*.pfx"};
			if (openFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				this.fldPFXFile.Text = openFileDlg.FileName;
			}
		}

		private void cmdSelectCERFile_Click(object sender, System.EventArgs e)
		{
			OpenFileDialog openFileDlg = new OpenFileDialog {Title = "Select a CER file", Filter = "CER Certificate|*.cer"};
			if (openFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				this.fldCERFile.Text = openFileDlg.FileName;
			}
		}
	}
}